import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge, PageHeader, Layout } from 'antd';
import '@/assets/css/settings';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as ProcessQualityControlService from '../../../axios/ProcessQualityControl'
import * as APIServiceYQ from '../../../axios/api_yq'
import * as APIService from '../../../axios/api'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import { statusList } from '../../../utils/global';

import EditRowTable from '../../../components/EditRowTable';
import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')

class SelfCheckingList extends Component {
  state = {
    formData: {},
    searchItem: {},
    dataSource: [],
    pageSize: 10,
    pageNum: 1,
    total: 0,
    clickSaveFlag: false,   // true 禁用  false 启用
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        align: 'center',
        width: 50,
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },
      {
        title: '检验项目',
        dataIndex: 'checkItem',
        width: 400,
        sorter: (a, b) => compareString(a.checkItem, b.checkItem)
      },
      {
        title: '检查情况',
        width: 200,
        editable: true,
        // allowEllipsis: true,
        dataIndex: 'checkSituation',
        sorter: (a, b) => compareString(a.checkSituation, b.checkSituation)
      },
      {
        title: '纠正措施',
        width: 200,
        editable: true,
        // allowEllipsis: true,
        dataIndex: 'correctiveAction',
        sorter: (a, b) => compareString(a.correctiveAction, b.correctiveAction)
      },
      {
        title: '结果',
        width: 100,
        dataIndex: 'checkResult',
        sorter: (a, b) => compareString(a.checkResult, b.checkResult),
        render: (text, record) =>
          text == '0' ? <Badge status='processing' text={<span style={{ color: '#1890ff' }}>{'新建'}</span>} />
            : text == '2' ? <Badge status="warning" text={<span style={{ color: '#ffc440' }}>{'不合格'}</span>} />
              : text == '1' ? <Badge status="success" text={<span style={{ color: '#1e8e3e' }}>{'合格'}</span>} />
                : text === '3' ? <Badge color='red' text={<span style={{ color: 'red' }}>{'删除'}</span>} /> : ''
      },
      {
        title: '操作',
        dataIndex: 'opts',
        width: 100,
        render: (text, record) => {
          const { editingKey, clickSaveFlag } = this.state;
          const editable = record.id === editingKey;
          return editable ? (
            <span>
              <a
                disabled={clickSaveFlag}
                onClick={() => {
                  this.handleSave(record)
                }}
                style={{ marginRight: 8 }}
              >
                保存
              </a>
              <Divider type='vertical' />
              <a onClick={() => this.cancel()}>取消</a>
            </span>
          ) : (
            <span>
              <a disabled={editingKey !== ''} onClick={() => this.edit(record.id)}>
                编辑
              </a>
            </span>
          );
        }
      },
      { dataIndex: '' }
    ],
    editingKey: '',
    selectedRows: [],
    selectedRowKeys: [],
    btnLoading: false,
  };
  componentDidMount() {
    console.log(this.props.location)
    this.setState({
      formData: this.props.location?.data?.record ? this.props.location.data.record : JSON.parse(localStorage.getItem('SelfCheckingList')).record,
      searchItem: this.props.location?.data?.searchItem ? this.props.location.data.searchItem : JSON.parse(localStorage.getItem('SelfCheckingList')).searchItem,
    }, this.fetch)
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  //初始化加载数据
  fetch = () => {
    this.setState({ loading: true })
    const { formData } = this.state
    ProcessQualityControlService.findFromCheckDetails(formData.uniquetype).then(res => {
      if (res.data.code != 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      let dataSource = res.data.data
      this.setState({
        dataSource,
        loading: false
      })
    })
  }
  // 点击编辑按钮
  edit = (id) => { this.setState({ editingKey: id }); }
  // 点击取消按钮
  cancel = () => {
    this.setState({ editingKey: '' });
  };

  // 保存
  handleSave = (row) => {
    // console.log(row, 'row')
    this.setState({ clickSaveFlag: true })
    this.editTable1.validateFields((err, value) => {
      if (err) return
      this.newOrCompile({ ...row, ...value })
    })
  };
  //编辑接口
  newOrCompile = (value) => {
    const { formData } = this.state
    if (value.id == '自检表') {
      delete value.id
    }
    value.masterId = formData.id
    // console.log(value, 'newOrCompile')
    ProcessQualityControlService.updateFromCheckDetails(value).then((item) => {
      this.setState({ clickSaveFlag: false })
      if (item.data.code === 200) {
        openSuccessModal(item.data.msg)
        this.fetch()
        this.setState({ editingKey: '' })
      } else {
        openModalMessage('error', item.data.msg)
      }
    })
  }

  loadData = (value, dataSource) => {
    console.log(value, dataSource)
    this.newOrCompile(value)
  }
  // 打开详情页
  openDetails = (record) => {

    // const { searchItem, dataSource } = this.state
    // let data = { title: '123123', searchItem, queryForm: { dataSource }, path: 'ProcessQualityControl' }
    // localStorage.setItem('SelfChecking_Report', JSON.stringify(data))
    // this.props.history.push({ pathname: "/SelfChecking_Report", data })

    const { searchItem, dataSource, formData } = this.state
    let data = { title: formData?.batchNo + ' - ' + formData?.procedureName + ' - 自检表单', searchItem, queryForm: { dataSource, formData }, path: 'SelfCheckingList' }
    localStorage.setItem('SelfChecking_Report', JSON.stringify(data))
    this.props.history.push({ pathname: "/SelfChecking_Report", data })
  }
  render() {
    const { loading, dataSource, columns, formData, searchItem, editingKey } = this.state;

    return (
      <div>
        <BasicLayoutSearch>
          <PageHeader
            style={{ padding: '4px 24px' }}
            onBack={() => this.props.history.push({ pathname: '/ProcessQualityControl', data: { selfSearchItem: searchItem, activeKey: '1' } })}
            title={<div>{formData?.batchNo + ' - ' + formData?.procedureName + ' - 自检表单'}</div>}
            extra={<Button type='primary' icon='eye' onClick={this.openDetails}>查看报表</Button>}
          >
          </PageHeader>
        </BasicLayoutSearch>
        <Layout className="layout-model">
          <EditRowTable
            dataSource={dataSource}
            columns={columns}
            ref={node => (this.editTable1 = node)}
            rowKey={(record) => record.id}
            editingKey={editingKey}
            pagination={false}
            allowDrafting={true}
            allowEditable={this.loadData}
            loading={loading}
            scroll={{ y: 700, x: 500 }}
          />
        </Layout>
      </div>
    );
  }
}
export default Form.create()(withRouter(SelfCheckingList));